﻿using Aspose.Words;
using Aspose.Words.Tables;
using NPOI.SS.Formula.Functions;
using SRB.Tg.Operate;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Teigha.DatabaseServices;
using DataColumn = System.Data.DataColumn;
using DataTable = System.Data.DataTable;

namespace SRB.Tg.Model.Member.WordDocument
{
    public class ProjectDocument
    {
        Document doc = null;
        static string wordPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "WordDemo";
        string bridgeId;
        string mainId;
        string projectId;
        DataTable dt;
        DataTable bridgeMaindt;
        DataTable bridgdt;
        AsposeWordTools asposeWordTools = new AsposeWordTools();
        public ProjectDocument(string _bridgeId, string _appPath, out string bridge_type)
        {
            if (!Directory.Exists(_appPath))
            {
                // 文件夹不存在，创建它
                Directory.CreateDirectory(_appPath);
            }
            bridgeId = _bridgeId;
            string sqlMainId = "select * from busi_bridge where id='" + _bridgeId + "' ";
            bridgdt = MySqlHelper.ExecuteDataTable(sqlMainId, CommandType.Text);
            mainId = bridgdt.Rows[0]["main_id"].ToString();
            string sqlprojectId = "select * from busi_bridge_main where id='" + mainId + "' ";
            bridgeMaindt = MySqlHelper.ExecuteDataTable(sqlprojectId, CommandType.Text);
            projectId = bridgeMaindt.Rows[0]["project_id"].ToString();
            bridge_type = bridgeMaindt.Rows[0]["bridge_type"].ToString();
            string sqlproject = "select * from busi_project where id='" + projectId + "' ";
            dt = MySqlHelper.ExecuteDataTable(sqlproject, CommandType.Text);
        }

        public string DrawingCoverDocument(string savePath, string bridge_type)
        {
            try
            {
                doc = new Document(wordPath + "\\封面.docx");
                //项目全称
                string project_full_name = dt.Rows[0]["project_full_name"].ToString();
                string phase = dt.Rows[0]["design_phase"].ToString();
                string sqlfindphase = "select * from sys_dict_item a inner join sys_dict b on a.dict_id=b.id where b.dict_code='phase'";
                string design_phase = FinddictItem(sqlfindphase, phase);
                asposeWordTools.FillTableWithText(doc, "project_full_name", project_full_name);
                //FillTableWithText(doc, "project_overview", project_overview);
                if (bridge_type == "5")
                {
                    design_phase = "装配式灯光桥" + design_phase;
                }
                //封面名
                asposeWordTools.FillTableWithText(doc, "design_phase", design_phase);
                // 获取当前日期
                DateTime now = DateTime.Now;

                // 转换为中文格式
                string chineseDate = ConvertToChineseDate(now);
                asposeWordTools.FillTableWithText(doc, "datatime", chineseDate);
                doc.Save(savePath, SaveFormat.Docx);
            }
            catch (Exception ex)
            {
                Console.WriteLine("出现错误: " + ex.Message);
            }
            return savePath;
        }

        public string DrawingCatalogDocument(string savePath)
        {
            try
            {
                doc = new Document(wordPath + "\\目录.docx");
                //页眉
                string project_full_name = dt.Rows[0]["project_full_name"].ToString();
                project_full_name = project_full_name.Replace("\n", "");
                asposeWordTools.FillTableWithText(doc, "Heading", project_full_name);
                //图纸配置
                string sqlproject = "select name,drawing_no,pages,remark from busi_bridge_catalog where bridge_id='" + bridgeId + "' ";
                dt = MySqlHelper.ExecuteDataTable(sqlproject, CommandType.Text);
                asposeWordTools.FillTableWithDataTable(doc, 0, dt,21, 1, 1);
                doc.Save(savePath, SaveFormat.Docx);
            }
            catch (Exception ex)
            {
                Console.WriteLine("出现错误: " + ex.Message);
            }
            return savePath;
        }

        public string DrawingPortableDescriptionDesignDocument(string savePath)
        {
            try
            {
                doc = new Document(wordPath + "\\设计说明_机场桥.docx");

                string project_full_name = dt.Rows[0]["project_full_name"].ToString();
                project_full_name = project_full_name.Replace("\n", "");
                string project_overview = dt.Rows[0]["project_overview"].ToString();
                //页眉
                asposeWordTools.FillTableWithText(doc, "Heading", project_full_name);
                //项目概况
                asposeWordTools.FillTableWithText(doc, "project_overview", project_overview);

                //跨径布局
                string sqlconnection = "select expression,structural_id from busi_connection where bridge_id='" + bridgeId + "' and status = 0";
                DataTable connectiondt = MySqlHelper.ExecuteDataTable(sqlconnection, CommandType.Text);
                string expression = GetExpressionsConcatenated(connectiondt);

                //桁架高
                string beam_height = bridgdt.Rows[0]["beam_height"].ToString();

                //节间长度
                string beam_section_width = bridgdt.Rows[0]["beam_section_width"].ToString();

                string structural_id = connectiondt.Rows[0]["structural_id"].ToString();
                string sqlupper = "select main_ibeam_structural from busi_upper_part_structural where id='" + structural_id + "' ";
                DataTable upperdt = MySqlHelper.ExecuteDataTable(sqlupper, CommandType.Text);

                string main_ibeam_structural = upperdt.Rows[0]["main_ibeam_structural"].ToString();
                string sqlibeam = "select * from busi_ibeam_structural where id='" + main_ibeam_structural + "' ";
                DataTable ibeamdt = MySqlHelper.ExecuteDataTable(sqlibeam, CommandType.Text);

                //桁架宽度
                string span_width = ibeamdt.Rows[0]["span_width"].ToString();
                ////判断是否有可变宽
                //string span_width_segment = ibeamdt.Rows[0]["span_width_segment"].ToString();
                //if (span_width_segment.Contains("(")) 
                //{
                //    int openParenIndex = span_width_segment.IndexOf('(');
                //    int closeParenIndex = span_width_segment.IndexOf(')', openParenIndex);

                //    string content = span_width_segment.Substring(openParenIndex + 1, closeParenIndex - openParenIndex - 1);
                //    span_width = "定宽" + span_width+ "m，变宽"+ content;
                //}

                //弦杆类型
                List<string> straight_web_bar_type = ibeamdt.AsEnumerable().SelectMany(row => new[]
                {
                    row.Field<string>("straight_web_bar_type"),
                    row.Field<string>("reinforced_straight_web_bar_type"),
                }).Distinct().ToList();
                List<string> straight_materialcategoryList = new List<string>();
                string straight_web_member_type = "";
                for (int i = 0; i < straight_web_bar_type.Count; i++)
                {
                    string web_member_type_code = straight_web_bar_type[i];
                    string sqlmaterialcategory = "select name from busi_material_category where code='" + web_member_type_code + "' ";
                    straight_web_member_type = MySqlHelper.ExecuteDataTable(sqlmaterialcategory, CommandType.Text).Rows[0]["name"].ToString();
                    straight_materialcategoryList.Add(straight_web_member_type);
                }
                if (straight_materialcategoryList.Count == 1)
                {
                    straight_web_member_type = "均采用" + straight_materialcategoryList[0];
                }
                else if (straight_materialcategoryList.Count > 1)
                {
                    straight_web_member_type = "采用" + string.Join("和", straight_materialcategoryList);
                }

                //腹杆类型
                List<string> web_bar_type = ibeamdt.AsEnumerable().SelectMany(row => new[]
                {
                    row.Field<string>("diagonal_brace_type"),
                    row.Field<string>("reinforced_diagonal_brace_type"),
                    row.Field<string>("web_member_type")
                }).Distinct().ToList();
                List<string> materialcategoryList = new List<string>();
                string web_member_type = "";
                for (int i = 0; i < web_bar_type.Count; i++)
                {
                    string web_member_type_code = web_bar_type[i];
                    string sqlmaterialcategory = "select name from busi_material_category where code='" + web_member_type_code + "' ";
                    web_member_type = MySqlHelper.ExecuteDataTable(sqlmaterialcategory, CommandType.Text).Rows[0]["name"].ToString();
                    materialcategoryList.Add(web_member_type);
                }
                if (materialcategoryList.Count == 1)
                {
                    web_member_type = "均采用" + materialcategoryList[0];
                }
                else if (materialcategoryList.Count > 1)
                {
                    web_member_type = "采用" + string.Join("和", materialcategoryList);
                }

                //坡度
                string slope = bridgeMaindt.Rows[0]["bridge_slope"].ToString();

                //标准节段长度
                double beamSectionWidth = double.Parse(beam_section_width);
                int beamSectionLength = (int)(10 / beamSectionWidth);
                beamSectionLength = beamSectionLength < 3 ? 3 : beamSectionLength;
                double beamSectionLength_text = beamSectionLength * beamSectionWidth;

                string Main_beam_construction = string.Format(Const.Main_beam_construction, expression, beam_height,
                    beam_section_width, span_width, straight_web_member_type,
                    web_member_type, slope, beamSectionLength_text.ToString());
                asposeWordTools.FillTableWithText(doc, "Main_beam_construction", Main_beam_construction);

                //钢墩以及桥台个数
                string sqlspan = "select span_type from busi_span where bridge_id='" + bridgeId + "' and status = 0";
                DataTable spandt = MySqlHelper.ExecuteDataTable(sqlspan, CommandType.Text);
                int countA = spandt.AsEnumerable().Count(row => row.Field<string>("span_type") == "A");
                int countP = spandt.AsEnumerable().Count(row => row.Field<string>("span_type") == "P");

                string sqlportable = "select psbp.steel_tower_type,psbpi.dia,psbpi.is_add_steel_casing from " +
                    "busi_portable_steel_bridge_pier psbp " +
                    "left join busi_span s " +
                    "on psbp.span_id = s.id " +
                    "left join busi_portable_steel_bridge_pile psbpi " +
                    "on psbp.id = psbpi.pier_id " +
                    "where s.bridge_id='" + bridgeId + "' ";
                DataTable steelTowerTypedt = MySqlHelper.ExecuteDataTable(sqlportable, CommandType.Text);
                //判断是否存在Y型钢塔
                bool containsYsteelTower = steelTowerTypedt.AsEnumerable().Any(row => row.Field<string>("steel_tower_type") == "2");
                string pier_y_description = "";
                string pier_y_description_2 = "";
                string pier_y_description_3 = "";
                if (containsYsteelTower)
                {
                    pier_y_description = "四个墩墩顶Y型支腿尺寸一致，";
                    pier_y_description_2 = "Y型的两支腿之间建议采用临时结构或钢索拉紧，以保证其间距，方便钢梁安装。";
                    pier_y_description_3 = "首先吊装墩顶Y型支腿上钢梁，然后对称悬臂施工，两侧不对称长度不超过" + beamSectionLength_text + "m（标准节段）。";
                }
                asposeWordTools.FillTableWithText(doc, "pier_y_description_2", pier_y_description_2);
                asposeWordTools.FillTableWithText(doc, "pier_y_description_3", pier_y_description_3);

                string Steel_tower_construction = string.Format(Const.Steel_tower_construction, countP.ToString(), countA.ToString(), pier_y_description);
                asposeWordTools.FillTableWithText(doc, "Steel_tower_construction", Steel_tower_construction);

                string Support_construction = string.Format(Const.Support_construction, countP.ToString());
                asposeWordTools.FillTableWithText(doc, "Support_construction", Support_construction);

                //桩基直径
                string dia = "";
                List<int> diaList = steelTowerTypedt.AsEnumerable().SelectMany(row => new[]
                {
                    row.Field<int>("dia"),
                }).Distinct().ToList();

                var formattedList = diaList.Select(d => (d * 0.01).ToString("0.##") + "m").ToList();
                // 根据 diaList 的元素个数生成最终字符串
                if (diaList.Count == 1)
                {
                    dia = $"均采用直径{formattedList[0]}的桩基";
                }
                else
                {
                    dia = $"采用直径{string.Join("、", formattedList)}的桩基";
                }

                //判断是否添加护筒
                bool isaddsteelcasing = steelTowerTypedt.AsEnumerable().Any(row => row.Field<string>("is_add_steel_casing") == "1");
                string steel_casing_description = "";
                if (isaddsteelcasing)
                {
                    steel_casing_description = "每根桩基设置钢护筒，护筒长度壁小于桩长的50%，护筒间采用φ400×8的钢管连接，起到对出露桩基混凝土进行保护和围挡的作用。";
                }

                string Base_construction = string.Format(Const.Base_construction, dia, steel_casing_description);
                asposeWordTools.FillTableWithText(doc, "Base_construction", Base_construction);

                doc.Save(savePath, SaveFormat.Docx);
            }
            catch (Exception ex)
            {
                Console.WriteLine("出现错误: " + ex.Message);
            }
            return savePath;
        }

        public string DrawingDescriptionDesignDocument(string savePath)
        {
            try
            {
                doc = new Document(wordPath + "\\设计说明.docx");

                string project_full_name = dt.Rows[0]["project_full_name"].ToString();
                project_full_name = project_full_name.Split(new[] { "\n" }, StringSplitOptions.None)[0];
                //project_full_name = project_full_name.Replace("\n", "");
                string project_overview = dt.Rows[0]["project_overview"].ToString();
                //页眉
                asposeWordTools.FillTableWithText(doc, "Heading", project_full_name);
                string bridge_name = bridgeMaindt.Rows[0]["name"].ToString();
                asposeWordTools.FillTableWithText(doc, "bridge_name", bridge_name);
                //项目概况
                asposeWordTools.FillTableWithText(doc, "project_overview", project_overview);

                //设计依据
                string design_consideration = Const.design_consideration;
                asposeWordTools.FillTableWithText(doc, "design_consideration", design_consideration);

                string slope = bridgeMaindt.Rows[0]["bridge_slope"].ToString();

                //设计基准期
                string design_reference_period = bridgeMaindt.Rows[0]["design_reference_period"].ToString();

                //荷载标准
                string load_standard = bridgeMaindt.Rows[0]["load_standard"].ToString();
                string sqlfindload_standard = "select * from sys_dict_item a inner join sys_dict b on a.dict_id=b.id where b.dict_code='bridge_load'";

                load_standard = FinddictItem(sqlfindload_standard, load_standard);
                //桥宽
                string width = bridgdt.Rows[0]["width"].ToString();

                //主要技术指标
                string technical_index = string.Format(Const.technical_index, design_reference_period, load_standard, slope, slope, width);
                asposeWordTools.FillTableWithText(doc, "technical_index", technical_index);

                //混凝土
                string sql_pier_concrete_no = "select pile_concrete_no,pile_cap_concrete_no,beam_concrete_no,pier_body_concrete_no,abutment_concrete_no " +
                    "from vi_pier_concrete_no a left join vi_abutment_concrete_no b on a.bridge_id=b.bridge_id where a.bridge_id='" + bridgeId + "'";
                DataTable pier_concrete_no_dt = MySqlHelper.ExecuteDataTable(sql_pier_concrete_no, CommandType.Text);
                DataTable concrete_nodt = new DataTable();
                concrete_nodt.Columns.Add("位置", typeof(string));
                concrete_nodt.Columns.Add("规格", typeof(string));
                concrete_nodt.Columns.Add("备注", typeof(string));
                var map = pier_concrete_no_dt.AsEnumerable()
                            .SelectMany(row => pier_concrete_no_dt.Columns.Cast<DataColumn>()
                                .Select(column => new { Value = row[column], ColumnName = column.ColumnName }))
                            .GroupBy(x => x.Value)
                            .ToDictionary(
                                g => g.Key,
                                g => g.Select(x => x.ColumnName).Distinct().ToList()
                            );
                foreach (var entry in map)
                {
                    if (entry.Key != null && entry.Key.ToString() != "") 
                    {
                        string sqlfindphase = "select * from sys_dict_item a inner join sys_dict b on a.dict_id=b.id where b.dict_code='concrete_grade'";
                        string value = FinddictItem(sqlfindphase, entry.Key.ToString());
                        string name = string.Join(", ", entry.Value);
                        name = name.Replace("pile_concrete_no", "桩基");
                        name = name.Replace("pile_cap_concrete_no", "承台");
                        name = name.Replace("beam_concrete_no", "盖梁");
                        name = name.Replace("pier_body_concrete_no", "引桥墩");
                        name = name.Replace("abutment_concrete_no", "桥台");
                        concrete_nodt.Rows.Add(name, value,"");
                    }
                }
                concrete_nodt.Rows.Add("预制桥面板", "C55","");
                concrete_nodt.Rows.Add("桥面板现浇接缝", "C55", "自密实微膨胀");
                concrete_nodt.Rows.Add("伸缩缝后浇带", "C55", "钢纤维混凝土");
                asposeWordTools.FillTableWithDataTableByBookmark(doc, "table1",0, concrete_nodt, concrete_nodt.Rows.Count, 1, 1);

                sql_pier_concrete_no = "select " +
                    "pile_concrete_protect_layer,pile_cap_concrete_protect_layer,beam_concrete_protect_layer,pier_body_concrete_protect_layer, " +
                    "abutment_concrete_protect_layer from vi_pier_concrete_no a left join vi_abutment_concrete_no b on a.bridge_id=b.bridge_id where a.bridge_id='" + bridgeId + "'";
                DataTable pier_concrete_protect_layer_dt = MySqlHelper.ExecuteDataTable(sql_pier_concrete_no, CommandType.Text);
                DataTable concrete_protect_layerdt = new DataTable();
                concrete_protect_layerdt.Columns.Add("位置", typeof(string));
                concrete_protect_layerdt.Columns.Add("保护层厚度 (mm)", typeof(string));
                var map2 = pier_concrete_protect_layer_dt.AsEnumerable()
                            .SelectMany(row => pier_concrete_protect_layer_dt.Columns.Cast<DataColumn>()
                                .Select(column => new { Value = row[column], ColumnName = column.ColumnName }))
                            .GroupBy(x => x.Value)
                            .ToDictionary(
                                g => g.Key,
                                g => g.Select(x => x.ColumnName).Distinct().ToList()
                            );
                foreach (var entry in map2)
                {
                    if (entry.Key != null && entry.Key.ToString() != "")
                    {
                        string value = (double.Parse(entry.Key.ToString()) * 10).ToString();
                        string name = string.Join(", ", entry.Value);
                        name = name.Replace("pile_concrete_protect_layer", "桩基");
                        name = name.Replace("pile_cap_concrete_protect_layer", "承台");
                        name = name.Replace("beam_concrete_protect_layer", "盖梁");
                        name = name.Replace("pier_body_concrete_protect_layer", "桥墩");
                        name = name.Replace("abutment_concrete_protect_layer", "桥台");
                        concrete_protect_layerdt.Rows.Add(name, value);
                    }
                }
                concrete_protect_layerdt.Rows.Add("桥面板", 30);
                concrete_protect_layerdt = SortTableByColumnName(concrete_protect_layerdt, "保护层厚度 (mm)");
                asposeWordTools.FillTableWithDataTableByBookmark(doc, "table2", 1, concrete_protect_layerdt, concrete_protect_layerdt.Rows.Count, 1, 1);

                //路线总体设计
                string overall_design = string.Format(Const.overall_design, width, slope);
                asposeWordTools.FillTableWithText(doc, "overall_design", overall_design);

                //桥跨布置
                string start_station = Formatstation(double.Parse(bridgeMaindt.Rows[0]["start_station"].ToString()));
                string mid_station = Formatstation(double.Parse(bridgeMaindt.Rows[0]["mid_station"].ToString()));
                string end_station = Formatstation(double.Parse(bridgeMaindt.Rows[0]["end_station"].ToString()));
                
                //跨径布局
                string sqlconnection = "select expression,structural_id,section_length,structural_type_name from busi_connection where bridge_id='" + bridgeId + "' and status = 0";
                DataTable connectiondt = MySqlHelper.ExecuteDataTable(sqlconnection, CommandType.Text);
                string connection_type_name = connectiondt.Rows[0]["structural_type_name"].ToString();
                string expression = GetExpressionsConcatenated(connectiondt);

                double section_length = Convert.ToDouble(connectiondt.Compute("SUM(section_length)", string.Empty));
                string sqlspan = "select span_type,pier_type_name,bridge_abutment_type_name,structural_id from busi_span where bridge_id='" + bridgeId + "' and status = 0";
                DataTable spandt = MySqlHelper.ExecuteDataTable(sqlspan, CommandType.Text);
                List<string> pier_type_nameList = spandt.AsEnumerable().Where(row => row.Field<string>("span_type") == "P").Select(row => row.Field<string>("pier_type_name")).Distinct().ToList();
                string pier_type_name = "";
                if (pier_type_nameList.Count == 1)
                {
                    pier_type_name = pier_type_nameList[0];
                }
                else if (pier_type_nameList.Count > 1)
                {
                    pier_type_name = string.Join("、", pier_type_nameList);
                }
                List<string> bridge_abutment_type_nameList = spandt.AsEnumerable().Where(row => row.Field<string>("span_type") == "A").Select(row => row.Field<string>("bridge_abutment_type_name")).Distinct().ToList();
                string bridge_abutment_type_name = "";
                if (bridge_abutment_type_nameList.Count == 1)
                {
                    bridge_abutment_type_name = bridge_abutment_type_nameList[0];
                }
                else if (bridge_abutment_type_nameList.Count > 1)
                {
                    bridge_abutment_type_name = string.Join("、", bridge_abutment_type_nameList);
                }
                connection_type_name = RemoveDigits(connection_type_name);
                pier_type_name = RemoveDigits(pier_type_name);
                bridge_abutment_type_name = RemoveDigits(bridge_abutment_type_name);
                string span_arrangement = string.Format(Const.span_arrangement, start_station, mid_station, end_station, expression, section_length, connectiondt.Rows.Count, connection_type_name, pier_type_name, bridge_abutment_type_name);
                asposeWordTools.FillTableWithText(doc, "span_arrangement", span_arrangement);

                //钢主梁
                string steel_main_beam = Const.steel_main_beam;
                asposeWordTools.FillTableWithText(doc, "steel_main_beam", steel_main_beam);

                string steel_main_beam_length = Const.steel_main_beam_length;
                asposeWordTools.FillTableWithText(doc, "steel_main_beam_length", steel_main_beam_length);

                //桥面板
                string steel_bridge_deck = Const.steel_bridge_deck;
                asposeWordTools.FillTableWithText(doc, "steel_bridge_deck", steel_bridge_deck);

                //墩台
                string sqlpier_size = "SELECT CONCAT(ROUND(MIN(a.pier_height), 3), ' ≤h≤ ', ROUND(MAX(a.pier_height), 3)) AS pier_height_range,CONCAT(f.top_l * 0.01, '×', f.top_w * 0.01) as pier_body_size,f.top_thickness * 0.01 as pier_body_thickness,CONCAT(a.beam_l * 0.01, '×', a.beam_w * 0.01, '×', a.beam_height) as beam_size,CONCAT(g.pile_cap_length * 0.01, '×', g.pile_cap_width * 0.01, '×', a.pile_cap_height) as pile_cap_size,(d.dia*0.01) as dia,GROUP_CONCAT(c.name ORDER BY CAST(SUBSTRING(c.name, 2) AS UNSIGNED) SEPARATOR '、') AS names " +
                    "FROM busi_pier a " +
                    "LEFT JOIN busi_span c ON a.span_id = c.id " +
                    "LEFT JOIN busi_pier_structural b ON b.id = c.structural_id " +
                    "LEFT JOIN busi_pile_structural d ON b.pile_structural_id = d.id " +
                    "LEFT JOIN busi_beam_structural e ON b.beam_structural_id = e.id " +
                    "LEFT JOIN busi_pier_body_structural f ON b.pier_structural_id = f.id " +
                    "LEFT JOIN busi_pile_cap_structural g ON b.pile_cap_structural_id = g.id " +
                    "WHERE bridge_id='" + bridgeId + "' and c.span_type = 'P' " +
                    "GROUP BY beam_size,pile_cap_size,pier_body_size,pier_body_thickness,dia " +
                    "ORDER BY pier_height_range";
                DataTable pier_size_dt = MySqlHelper.ExecuteDataTable(sqlpier_size, CommandType.Text);
                asposeWordTools.FillTableWithDataTableByBookmark(doc, "table3", 6, pier_size_dt, pier_size_dt.Rows.Count, 1, 0);

                string pier_consideration = string.Format(Const.pier_consideration, pier_type_name, pier_size_dt.Rows.Count);
                asposeWordTools.FillTableWithText(doc, "pier_consideration", pier_consideration);

                //桩基直径
                List<string> bridge_abutmentList = spandt.AsEnumerable().Where(row => row.Field<string>("span_type") == "A").Select(row => row.Field<string>("structural_id")).Distinct().ToList();
                string abutment_structural_id = string.Join(",", bridge_abutmentList);
                string sqlabutment_structural = "SELECT b.dia FROM busi_abutment_structural a " +
                    "left join busi_pile_structural b " +
                    "on a.pile_structural_id = b.id " +
                    "where a.id in ('" + abutment_structural_id + "')";
                DataTable abutment_pile_dt = MySqlHelper.ExecuteDataTable(sqlabutment_structural, CommandType.Text);

                List<int> diaList = abutment_pile_dt.AsEnumerable().SelectMany(row => new[]
                {
                    row.Field<int>("dia"),
                }).Distinct().ToList();
                string abutment_dia = "";
                if (diaList.Count > 0) 
                {
                    var formattedList = diaList.Select(d => (d * 0.01).ToString("0.##") + "m").ToList();
                    // 根据 diaList 的元素个数生成最终字符串
                    if (diaList.Count == 1)
                    {
                        abutment_dia = $"桩基直径{formattedList[0]}。";
                    }
                    else
                    {
                        abutment_dia = $"桩基直径{string.Join("、", formattedList)}。";
                    }
                }
                string abutment_consideration = string.Format(Const.abutment_consideration, bridge_abutment_type_name, abutment_dia);
                asposeWordTools.FillTableWithText(doc, "abutment_consideration", abutment_consideration);

                AddColumnWithDefaultValue(concrete_protect_layerdt, "裂缝宽度限值 (mm)", "0.2");
                asposeWordTools.FillTableWithDataTableByBookmark(doc, "table4", 7, concrete_protect_layerdt, concrete_protect_layerdt.Rows.Count, 1, 1);


                doc.Save(savePath, SaveFormat.Docx);
            }
            catch (Exception ex)
            {
                Console.WriteLine("出现错误: " + ex.Message);
            }
            return savePath;
        }

        public string Formatstation(double value)
        {
            // 获取整数部分和小数部分
            int intPart = (int)Math.Floor(value);
            double decimalPart = value - intPart;

            // 将整数部分转换为字符串并拆分
            string intPartStr = intPart.ToString();
            string lastThreeDigits = intPartStr.Length > 3 ? intPartStr.Substring(intPartStr.Length - 3) : intPartStr;
            string leadingDigits = intPartStr.Length > 3 ? intPartStr.Substring(0, intPartStr.Length - 3) : "0";

            // 格式化小数部分
            string decimalPartStr = decimalPart.ToString("0.0000");

            // 拼接结果
            return $"K{leadingDigits}+{lastThreeDigits}.{decimalPartStr.Substring(2)}";
        }

        public string FinddictItem(string sql, string value)
        {
            System.Data.DataTable dt = MySqlHelper.ExecuteDataTable(sql, CommandType.Text);
            System.Data.DataRow[] dr = dt.Select("item_value='" + value + "'");
            string result = "";
            if (dr.Length > 0)
            {
                result = dr[0]["item_text"].ToString();
            }
            else
            {
                result = value;
            }
            return result;
        }

        public string ConvertToChineseDate(DateTime date)
        {
            // 数字到中文的映射
            string[] chineseNumbers = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };

            // 获取年份、月份
            int year = date.Year;
            int month = date.Month;

            // 将年份转换为中文
            string yearStr = ConvertNumberToChinese(year, chineseNumbers);
            string monthStr = chineseNumbers[month];

            return $"{yearStr}年{monthStr}月";
        }

        public string ConvertNumberToChinese(int number, string[] chineseNumbers)
        {
            // 将年份分解为个位数和十位数
            string numberStr = number.ToString();
            string result = "";

            foreach (char digit in numberStr)
            {
                result += chineseNumbers[digit - '0'];
            }

            return result;
        }

        public string GetExpressionsConcatenated(DataTable table)
        {
            StringBuilder sb = new StringBuilder();

            foreach (DataRow row in table.Rows)
            {
                if (sb.Length > 0)
                {
                    sb.Append("+");
                }

                sb.Append(row["expression"].ToString());
            }

            return sb.ToString();
        }

        public string RemoveDigits(string text)
        {
            return Regex.Replace(text, @"\d+", "");
        }

        public DataTable SortTableByColumnName(DataTable table, string columnName)
        {
            // 确保列名存在
            if (table.Columns.Contains(columnName))
            {
                // 使用 DefaultView 对 DataTable 进行排序
                DataView view = table.DefaultView;
                view.Sort = columnName; // 默认为升序排序
                return view.ToTable();
            }
            else
            {
                throw new ArgumentException($"Column '{columnName}' does not exist in the DataTable.");
            }
        }

        public void AddColumnWithDefaultValue(DataTable table, string columnName, string defaultValue)
        {
            // 添加新列到 DataTable
            DataColumn newColumn = new DataColumn(columnName, typeof(double));
            table.Columns.Add(newColumn);

            // 设置所有行的该列值为 defaultValue
            foreach (DataRow row in table.Rows)
            {
                row[columnName] = defaultValue;
            }
        }
    }
}
